<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;


use App\Models\Column;
use App\Models\ColumnTranslation;
use App\Models\Routes\Routes;
use Illuminate\Http\Request;
use App\Http\Requests\ColumnUpdateRequest;
use App\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use App\Services\QiniuServices;
use DB;

class ColumnsController extends AdminController
{
    /**
     * 分类列表
     * @return \Illuminate\Contracts\View\View
     */

    private $ispart;

    public function __construct()
    {
       $this->ispart =[1=>"lists",2=>"index",3=>null];
    }

    
    public function index()
    {
        return View::make('admin.category.index');
    }

    /**
     * 分类列表数据接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {
        $pid = $request->pid ?? 0;
        $created_at = $request->created_at ?? null;
        $lang = $request->get('lang', 'zh');
        $model = ColumnTranslation::query();
        if ($lang) {
            $model = $model->where('locale', $lang);
        }
        $model = $model->where('pid', $pid);
        if (!empty($created_at)) {
            $startime = substr($created_at, 0, 20);
            $endtime = substr($created_at, -20, 20);
            $model = $model->whereBetween('created_at', [$startime, $endtime]);
        }

        $res = $model->with(['children'=>function($query) use($lang){
            //$query->where('isdelete',0);
        }])->where(['isdelete'=>0])->where('listrule','!=','home')->orderBy('sort', 'asc')->get();





        return Response::json([ 'code' => 0, 'msg' => '正在请求中...',  'count' => $res->count(), 'data' => $res]);
    }

    /**
     * 添加栏目 View
     * @return \Illuminate\Contracts\View\View
     */
    public function create()
    {
        $categories = $this->getColumnClass();
        return View::make('admin.category.create', compact('categories'));
    }

    /**
     * 添加栏目
     * @param CategoryRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(Request $request)
    {
        $data = $request->except(['_token', 'file']);
 
        if($this->hasRoutes($data)){
            return Response::json(['code' => 1, 'msg' => '路由已被其他栏目使用!请重新换个URL规则']);
        }

       
        DB::beginTransaction();
        try {
   
            $Column = new Column();
			$Column->classname=$request->name;
            $sid = DB::table('column_translations')->max('sid');
            
    
            foreach (config('translatable.locales') as $locale => $item) {
                $Column->translateOrNew($locale)->name = $request->name;
                $Column->translateOrNew($locale)->sub_name = $request->sub_name;
                $Column->translateOrNew($locale)->pid = $request->pid;
                $Column->translateOrNew($locale)->sid = $sid + 1;
                $Column->translateOrNew($locale)->smalltype = $request->smalltype;
                $Column->translateOrNew($locale)->ispart = $request->ispart;
                $Column->translateOrNew($locale)->attribute = $request->attribute;
                $Column->translateOrNew($locale)->domain = $request->domain;
                $Column->translateOrNew($locale)->issend = $request->issend;
                $Column->translateOrNew($locale)->seo_title = $request->seo_title;
                $Column->translateOrNew($locale)->seo_key = $request->seo_key;
                $Column->translateOrNew($locale)->description = $request->description;
                $Column->translateOrNew($locale)->thumb = $request->thumb;
                $Column->translateOrNew($locale)->wapthumb = $request->wapthumb;
                $Column->translateOrNew($locale)->isdisplay = $request->isdisplay;
                $Column->translateOrNew($locale)->covertpl = $request->covertpl;
                $Column->translateOrNew($locale)->listtpl = $request->listtpl;
                $Column->translateOrNew($locale)->infotpl = $request->infotpl;
                $Column->translateOrNew($locale)->inforule = $request->inforule;
                $Column->translateOrNew($locale)->listrule = $request->listrule;
                $Column->translateOrNew($locale)->sort = $request->sort;
                $Column->translateOrNew($locale)->status = $request->status;
                $Column->translateOrNew($locale)->body = $request->body;
                $Column->translateOrNew($locale)->model = $request->model;
                $Column->translateOrNew($locale)->urls = $request->urls;
                $Column->translateOrNew($locale)->status = 1;
                $Column->translateOrNew($locale)->routename = $request->routename;				
				
            }
     
            $Column->save();
            $this->routes();

            DB::commit();
            return Response::json(['code' => 0, 'msg' => '添加成功']);
        } catch (\Exception $exception) {
            DB::rollback();
        }

        return Response::json(['code' => 1, 'msg' => '添加失败']);


    }

    public function edit(Request $request)
    {

        $id = (int)$request->id;
        $category = ColumnTranslation::where('id', $id)->firstOrFail();
        $categories = $this->getColumnClass();
        return View::make('admin.category.edit', compact('category', 'categories'));
    }


    public function update(ColumnUpdateRequest $request)
    {
        $id = (int)$request->id;
        $data = $request->except(['_token', 'file']);
        $category = ColumnTranslation::where('id', $id)->firstOrFail();
        $column_mid=$category->column_mid;
 
		
       // DB::beginTransaction();
        //try {

			//更新公共参数
            $Column = Column::where('mid',$column_mid)->first();
			$Column->classname=$request->name;
            foreach (config('translatable.locales') as $locale => $item) {
					if(!$Column->hasTranslation($locale)){
					$Column->translateOrNew($locale)->name = $request->name;
					$Column->translateOrNew($locale)->sub_name = $request->sub_name;
					$Column->translateOrNew($locale)->pid = $data['pid'];
					$Column->translateOrNew($locale)->sid = $category->sid;
					$Column->translateOrNew($locale)->smalltype = $request->smalltype;
					$Column->translateOrNew($locale)->ispart = $request->ispart;
					$Column->translateOrNew($locale)->attribute = $request->attribute;
					$Column->translateOrNew($locale)->domain = $request->domain;
					$Column->translateOrNew($locale)->issend = $request->issend;
					$Column->translateOrNew($locale)->seo_title = $request->seo_title;
					$Column->translateOrNew($locale)->seo_key = $request->seo_key;
					$Column->translateOrNew($locale)->description = $request->description;
					$Column->translateOrNew($locale)->thumb = $request->thumb;
					$Column->translateOrNew($locale)->wapthumb = $request->wapthumb;
					$Column->translateOrNew($locale)->isdisplay = $request->isdisplay;
					$Column->translateOrNew($locale)->covertpl = $request->covertpl;
					$Column->translateOrNew($locale)->listtpl = $request->listtpl;
					$Column->translateOrNew($locale)->infotpl = $request->infotpl;
					$Column->translateOrNew($locale)->inforule = $request->inforule;
					$Column->translateOrNew($locale)->listrule = $request->listrule;
					$Column->translateOrNew($locale)->sort = $request->sort;
					$Column->translateOrNew($locale)->status = $request->status;
					$Column->translateOrNew($locale)->body = $request->body;
					$Column->translateOrNew($locale)->model = $request->model;
					$Column->translateOrNew($locale)->urls = $request->urls;
					$Column->translateOrNew($locale)->status = 0;
					$Column->translateOrNew($locale)->routename = $request->routename;	
					$Column->translateOrNew($locale)->method = $this->ispart[$data['ispart']];
				}else{
					$Column->translateOrNew($locale)->model = $data['model'];
					$Column->translateOrNew($locale)->pid = $data['pid'];
					$Column->translateOrNew($locale)->ismenu = $data['ismenu'];
					$Column->translateOrNew($locale)->ispart = $data['ispart'];
					$Column->translateOrNew($locale)->issend = $data['issend'];
					$Column->translateOrNew($locale)->method = $this->ispart[$data['ispart']];
					$Column->translateOrNew($locale)->listrule = $data['listrule'];
					$Column->translateOrNew($locale)->routename = $data['routename'];

                }
				 
		 

            }
			
		 
			
			$Column->save(); 
			$category = $category->update($data);
            //DB::commit();
            //更新路由
            $this->routes();
			 
            return Response::json(['code' => 0, 'msg' => '更新成功']);
        //} catch (\Exception $exception) {
          //  DB::rollback();
       // }
         return Response::json(['code' => 1, 'msg' => '更新失败']);
    }


    public function updateAjax(Request $request)
    {
        $id = (int)$request->id;
        $data = $request->except(['_token', 'file']);
        $category = ColumnTranslation::where('id', $id)->firstOrFail();
        $column_mid=$category->column_mid;
        DB::beginTransaction();
        try {
            
            $category->update($data);
             
            DB::commit();
            return Response::json(['code' => 0, 'msg' => '更新成功']);
        } catch (\Exception $exception) {
            DB::rollback();
        }
         return Response::json(['code' => 1, 'msg' => '更新失败']);
    }

   
    private function hasRoutes($data,$self = false){
        
        $listrule = $data['listrule'];
        $counts = Routes::where('path',$listrule)->count();

        if($counts>0) return true;
       
        return false;
    }
    
    //保存栏目路由
    private function routes(){
        DB::beginTransaction();
        try {
		   Routes::truncate();	
		   $column = ColumnTranslation::select('id','model','listrule','method','ispart','routename','column_mid')->get();
		   foreach($column as $item){
			  $comtroller =  ucwords("HomeController@forward");
			  if($item->listrule) Routes::create([
			  'controller'=>$comtroller, 
			  'path'=>$item->listrule.'.html',
			  'routename'=>$item->routename,
			  'column_id'=>$item->id,
			  'column_mid'=>$item->column_mid,
			  ]);
			}
            DB::commit();
			return true;
        } catch (\Exception $exception) {
            DB::rollBack();
        }
        return false;
    }

    //更新栏目路由
    private function updateRoutes($id){
        DB::beginTransaction();
        try {
		   $column = ColumnTranslation::where('id',$id)->firstOrFail();
		   Routes::where('column_id', $id)->delete();
		   $comtroller =  ucwords($column->model)."Controller@".$this->ispart[$column->ispart];
		   Routes::create(['AdminController'=>$comtroller, 'path'=>$column->listrule.'.html','column_id'=>$id]);
           DB::commit();
        } catch (\Exception $exception) {
           DB::rollBack();
        }
    }





    /**
     * 删除栏目
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request,QiniuServices $qiniu)
    {
        $ids = (array)$request->get('ids');
        if (empty($ids)) {
            return Response::json(['code' => 1, 'msg' => '请选择删除项']);
        }
         
		DB::beginTransaction();
        try {
			
			  foreach($ids as $id){
			
				$category = ColumnTranslation::where('id', $id)->firstOrFail();
				$column = Column::where('mid', $category->column_mid)->firstOrFail();
				foreach($column->translations as $item){
					//删除产品资源
					$qiniu->objFromDelete($item);

				}
				Column::destroy($category->column_mid);
				
				//删除路由
				Routes::where('column_mid', $category->column_mid)->delete();

			  }

			DB::commit();	
			
			return Response::json(['code' => 0, 'msg' => '删除成功']);

        } catch (\Exception $exception) {
            DB::rollBack();
        }
		
		
		return Response::json(['code' => 403, 'msg' => '删除失败']);

		
    }

}
